package com.tencreat.mq;

import com.rabbitmq.client.Channel;
import com.tencreat.common.enums.ActionMessageType;
import com.tencreat.common.utils.bean.ActionMessage;
import com.tencreat.mq.message.*;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.util.Objects;

/**
 * 系统事件Action消费者
 */
@Service
@RabbitListener(queues = "base-mall.user.action.name")
@RequiredArgsConstructor
@Slf4j
public class ActionMessageConsumer {

    private final ActionMessageLogin actionMessageLogin;
    private final ActionMessageRegister actionMessageRegister;
    private final ActionMessageAdminLogin actionMessageAdminLogin;
    private final ActionMessageCustomerCreate messageCustomerCreate;

    @RabbitHandler(isDefault=true)
    public void handle(Message message, Channel channel) throws Exception{
        log.info("进入系统事件消息处理--------------------------------------");
        ByteArrayInputStream byteInt = new ByteArrayInputStream(message.getBody());
        ObjectInputStream objInt = new ObjectInputStream(byteInt);
        ActionMessage actionMessage = (ActionMessage) objInt.readObject();

        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        //信息为空,丢弃该信息
        if (Objects.isNull(actionMessage)) {
            log.info("消息为空,手动丢弃该消息....");
            channel.basicNack(deliveryTag, false, false);
            return;
        }
        // 处理业务
        if(actionMessage.getType().equals(ActionMessageType.REGISTER)){
            actionMessageRegister.dealMessage(actionMessage);
        }
        else if(actionMessage.getType().equals(ActionMessageType.LOGIN)){
            actionMessageLogin.dealMessage(actionMessage);
        }
        else if(actionMessage.getType().equals(ActionMessageType.ADMIN_LOGIN)){
            actionMessageAdminLogin.dealMessage(actionMessage);
        }
        else if(actionMessage.getType().equals(ActionMessageType.CUSTOMER_CREATE)){
            messageCustomerCreate.dealMessage(actionMessage);
        }


        channel.basicAck(deliveryTag, false);
    }
}
